package com.neusoft.weixin.service.account;


import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.neusoft.common.util.UUIDGenerator;
import com.neusoft.weixin.repository.account.MessageDao;


/**
 * 消息管理类.
 * 
 */
@Service(value = "messageService")
public class MessageService {


	private Logger log = LoggerFactory.getLogger(MessageService.class);

	@Autowired
	private MessageDao messageDao;
	
	public String getMessageByMenuId(String menuId) throws Exception{
		log.info("获取指定菜单的消息");
		List<Map> message = messageDao.getMessageByMenuId(menuId);
		if ( null == message || message.size() == 0 ){
			return null;
		}
		
		String message_id = (String) message.get(0).get("MESSAGE_ID");
		return message_id;
	}
	
	public void saveMessage(JSONObject message){
		
		log.info("判断消息是否存在");
		String messageId = (String) message.get("MESSAGE_ID");
		if ( null == messageId ||  messageId.isEmpty() ){
			messageId = UUIDGenerator.getUUID();
			message.put("MESSAGE_ID", messageId);
			//设置消息类型
			message.put("MESSAGE_TYPE", "news");
			log.info("保存消息");
			messageDao.insertMessage(message);
		}
		
		log.info("重置内容的MESSAGE_ID");
		messageDao.resetContent(messageId);
		
		log.info("更新内容的MESSAGE_ID");
		JSONArray contents = message.getJSONArray("CONTENTS");
		List<String> contentIds = new ArrayList<String>();
		if ( contents.size() > 0 ){
			
			for ( int i = 0; i < contents.size(); i++ ){
				JSONObject content = contents.getJSONObject(i);
				String contentId = content.getString("CONTENT_ID");
				contentIds.add(contentId);
			}
			
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("messageId", messageId);
			map.put("contentIds", contentIds);
			
			messageDao.updateContent(map);

		}
		
		
		
	}
	
	
	

}
